package com.lagou.work.zookeeper.registry.impl;

import com.lagou.work.zookeeper.registry.RpcRegistryHandler;
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;

import java.util.List;

public class RpcRegistryHandlerImpl implements RpcRegistryHandler {

    private final String PATH = "/lagou/";

    public List<String> childrenList;

    public List<String> getChildrenList() {
        return childrenList;
    }

    private ZkClient initZk() {
        ZkClient zkClient = new ZkClient("127.0.0.1:2181");
        return zkClient;
    }

    private void createNode(ZkClient zkClient, String service, String ip, Integer port) {
        String providerPath = PATH + service + "/provider";
        boolean exists = zkClient.exists(providerPath);
        if(!exists) {
            zkClient.createPersistent(providerPath, true);
        }
        String instancePath = providerPath + "/" + ip + ":" + port;
        zkClient.createEphemeral(instancePath);
    }

    @Override
    public boolean registry(String service, String ip, Integer port) {
        ZkClient zkClient = this.initZk();
        createNode(zkClient, service, ip, port);
        return true;
    }

    @Override
    public List<String> discovery(String service) {
        ZkClient zkClient = this.initZk();
        String providerPath = PATH + service + "/provider";
        if (childrenList == null || childrenList.size() == 0) {
            childrenList = zkClient.getChildren(providerPath);
        }
        zkClient.subscribeChildChanges(providerPath, new IZkChildListener() {
            public void handleChildChange(String parentPath, List<String> list) throws Exception {
                System.out.println(parentPath + "的子节点列表发生了变化,变化后的子节点列表为"+ list);
                childrenList = list;
            }
        });
        return childrenList;
    }

}
